//
//  UserTableViewController.m
//  SNSDemo
//
//  Created by LZXuan on 15-5-21.
//  Copyright (c) 2015年 轩哥. All rights reserved.
//

#import "UserTableViewController.h"
#import "LZXHttpRequest.h"
#import "UserCell.h"
#import "UserModel.h"

#import "EGORefreshTableHeaderView.h"

#define kUrl @"http://10.0.8.8/sns/my/user_list.php?page=%ld&number=%ld"

@interface UserTableViewController ()<EGORefreshTableHeaderDelegate>
{
    NSMutableArray *_dataArr;//数据源数组
    LZXHttpRequest *_httpRequest;//下载请求
    
    //记录当前页
    NSInteger _currentPage;
    //是否正在刷新
    BOOL _isRefreshing;
    
    //ego 刷新视图
    EGORefreshTableHeaderView *_egoHeaderView ;
   
}
@end

@implementation UserTableViewController
- (void)dealloc {
    [_egoHeaderView release];
    [_dataArr release];
    [_httpRequest release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatHttpRequest];
      //导航条不透明
    self.navigationController.navigationBar.translucent = NO;
    
    //初始化
    _currentPage = 1;
    _isRefreshing = NO;
    
    //下载第一页数据
    [self downloadDataWithPage:_currentPage count:20];

    //创建刷新
    [self creatRefreshView];
    [self creatPullUpView];
}
#pragma mark - 创建EGO
- (void)creatRefreshView {
    //ego 第三库的下拉刷新库
    _egoHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0, -self.tableView.bounds.size.height, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
    //粘贴到 TableView的上方
    //设置代理
    _egoHeaderView.delegate = self;
    
    //记录最近一次刷新时间
    [_egoHeaderView refreshLastUpdatedDate];
    
    [self.tableView addSubview:_egoHeaderView];
}
#pragma mark - 滚动视图协议
//一直滚动调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //如果当前界面有多个滚动视图 要判断
    
    //传入 当前的滚动视图
    [_egoHeaderView egoRefreshScrollViewDidScroll:scrollView];
}
//松手 /停止拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [_egoHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}
#pragma mark - ego协议
//返回 是否正在进行刷新加载  返回YES表示正在刷新加载 那么-egoRefreshTableHeaderDidTriggerRefresh: 不会调用
//如果返回NO 表示没有刷新,才会开始刷新
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view {
    return _isRefreshing;
}
//开始刷新 和上面函数密切相关，只有上面返回了NO 下面才会调用
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view {
    _isRefreshing = YES;
    _currentPage = 1;
    //创建新的下载链接
    [self downloadDataWithPage:_currentPage count:20];
}
- (NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view {
    //返回当前的刷新的系统时间
    return [NSDate date];
}


#pragma mark -  点击加载更多

- (void)creatPullUpView {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(0, 0, self.tableView.bounds.size.width, 30);
    [button setTitle:@"点击加载更多" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableFooterView = button;
}
- (void)btnClick:(UIButton *)button {
    if (_isRefreshing) {
        return;
    }
    _isRefreshing = YES;
    _currentPage ++;//页码+1
    [self downloadDataWithPage:_currentPage count:20];
}



#pragma mark - 创建下载对象
- (void)creatHttpRequest {
    //数据源数组
    _dataArr = [[NSMutableArray alloc] init];
    _httpRequest = [[LZXHttpRequest alloc] init];

}
//按页下载数据
- (void)downloadDataWithPage:(NSInteger)page count:(NSInteger)count {
    //获取url
    NSString *url = [NSString stringWithFormat:kUrl,page,count];
    
    
    //下面使用block 的时候 存在相互引用问题，那么必须 一强一弱
    //否则导致死锁
    //arc下面 需要
    //__weak UserTableViewController *mySelf = self;
    
    //非arc 写成下面的形式
    
    __block UserTableViewController *mySelf = self;
    
    //下载对象去数据
    [_httpRequest downloadDataWithUrl:url success:^(LZXHttpRequest *httpRequest) {
        //下载完成会回调这个block
        //这个block就是下载完成之后 要解析 下载数据
        [mySelf downloadDataSuccessWithRequest:httpRequest];
        
    } failed:^(NSError *error) {
        //下载失败 回调
    }];
}

- (void)downloadDataSuccessWithRequest:(LZXHttpRequest *)httpRequest {
    //httpRequest.downloadData下载的数据
    if (httpRequest.downloadData) {
        
        if (_currentPage == 1) {
            //表示下载的是第一页数据
            //要清空之前的
            [_dataArr removeAllObjects];
        }
        
        //有数据
        //二进制数据 json 格式 要json解析
        //最外层是字典
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:httpRequest.downloadData options:NSJSONReadingMutableContainers error:nil];
        //获取所有用户
        NSArray *userArr = dict[@"users"];
        //遍历数组
        for (NSDictionary*userDict in userArr) {
            //数组中是字典
            //把每个字典数据放在model中
            UserModel *model = [[UserModel alloc] init];
           
            model.username = userDict[@"username"];
            model.uid = userDict[@"uid"];
            // /my/headimage.php?uid=82781图片地址是一般 要拼接一个完整的地址
            model.headimage = [@"http://10.0.8.8/sns" stringByAppendingString:userDict[@"headimage"]];
            [_dataArr addObject:model];
            [model release];
        }
        //下载完成数据 刷新表格
        [self.tableView reloadData];
        NSLog(@"已经下载:%ld条数据",_dataArr.count);
        
        //下载完成 停止刷新
        _isRefreshing = NO;
        //停止ego刷新
        [_egoHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
//获取每一行的cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"UserCell";//要和xib中一致
    UserCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        //加载xib 定制的cell
        cell = [[[NSBundle mainBundle] loadNibNamed:@"UserCell" owner:self options:nil] lastObject];
    }
    //填充cell
    UserModel *model = _dataArr[indexPath.row];
    [cell showDataWithModel:model];
    return cell;
}


/*
 "count": 10,
 "users": [
 {
 "uid": "122722",
 "username": "zhangcheng0111",
 "groupid": "6",
 "credit": "119",
 "experience": "109",
 "viewnum": "0",
 "friendnum": "0",
 "lastactivity": 0,
 "headimage": "/my/headimage.php?uid=122722",
 "realname": ""
 },
 {
 "uid": "82781",
 "username": "Erfangdong",
 "groupid": "7",
 "credit": "1262",
 "experience": "1252",
 "viewnum": "44",
 */


@end
